<template>
	<view style="height: 100vh; background: #181818; position: relative; color: #ffffff;">
		<bakc text="历史数据" :isReturn="true" textMLeft='margin-left: 130rpx;' />


		<!--选择日期的弹层-->
		<u-popup :round="30" bgColor='transparent' :show="show" @close="close" @open="open">
			<view class="popup_day" v-if="dateType =='day'">
				<switching @switchingTime='switchingTime' />
				<!--星期几-->
				<view style="height: 50rpx;"></view>
				<view class="week">
					<view class="item">一</view>
					<view class="item">二</view>
					<view class="item">三</view>
					<view class="item">四</view>
					<view class="item">五</view>
					<view class="item">六</view>
					<view class="item">日</view>
				</view>
				<view class="day">
					<view class="item_no" v-for="item in dayWeek -2"></view>
					<view class="item_no"></view>
					<view :class="[
					dataDateGrouping.get(index),
					{item:true},
					{active: index==selectDayIndex},
					{forbidden: isForbiddenDay(index)}]" v-for="(item,index) in lastDayMonth"
						@click="!isForbiddenDay(index) ? selectDayIndex=index : index=index">{{ index+1 }}</view>
				</view>
				<view class="btn" @click="verifyDay">确定</view>
			</view>

			<view class="popup_month" v-else-if="dateType=='month'">
				<switching dateType='year' @switchingTime='switchingTime' />
				<view style="height: 50rpx;"></view>
				<view class="month">
					<view :class="[
						dataDateGrouping.get(index),
						{item:true},{active: index==selectMonthIndex},{forbidden: isForbiddenYear(index)}]" v-for="(item,index) in 12"
						@click="!isForbiddenYear(index) ? selectMonthIndex=index : index=index ">{{ index+1 }}月</view>
				</view>
				<view class="btn" @click="verifyDay">确定</view>
			</view>

			<view class="popup_years" v-else>
				<view style="height: 120rpx;"></view>
				<view class="years">
					<view @click="selectYearIndex = index" :class="[{year_item:true},{active: index==selectYearIndex}]"
						v-for="(item,index) in 12">
						{{ beforeTwentyYear + index+1  }} 年
					</view>
				</view>
				<view style="height: 50rpx;"></view>
				<view class="btn" @click="verifyDay">确定</view>
			</view>
		</u-popup>


		<!--年份选择框-->
	<!-- 	<view>
			<u-picker style="background-color: #F0F0F0;" :show="pickerShow" :columns="columns" @cancel='pickerCancel' @confirm='confirmPicker'></u-picker>
		</view>
 -->



		<!--导航栏-->
		<view style="height: 30rpx;"></view>
		<view class="navigation">
			<view class="select_date">
				<view :class="[{border_left:true},{stats:true},{item: true,active:dateSelectIndex==0}]"
					@click="dateSelectIndexMethod(0,'day')">日</view>
				<view :class="[{stats:true},{item: true,active:dateSelectIndex==1}]"
					@click="dateSelectIndexMethod(1,'month')">月
				</view>
				<view :class="[{border_right:true},{stats:true},{item: true,active:dateSelectIndex==2}]"
					@click="dateSelectIndexMethod(2,'years')">年
				</view>
			</view>
		</view>



		<!--日期 图表-->
		<view class="date_table" @click="open">
			<view></view>
			<view style="display: flex; align-items: center; margin-right: 7px; position: relative; z-index: 9999;">
				<view>{{ nowDate }}</view>
				<image src="../../static/icon/yellow_bottom_jt.png"
					style="width:30rpx; height:30rpx; margin-top:4rpx;" />
			</view>

		</view>

		<!--图表组件 v-if="isShowChars"-->
		<uchars v-if="isShowChars" :dateUnit="dateType=='day' ? '日' : dateType=='month' ? '月' : '年' "
			:categorie='categories' :dataOne='dataOne' :dataTwo='dataTwo' :gasType='gasId' :avg='avg'
			:canvasIds='canvasIds' />
	</view>
</template>

<script>
	import {
		searchData,
		searchDayAvgData
	} from '@/config/api.js';
	export default {
		data() {
			return {

				// columns: [
				// 	['2012', '2013', '2014','2015','2016','2017','2018','2019']
				// ],

				//ucahrs 的图表id
				canvasIds: {
					canvasOneId: 'nHLyuIhBZnCVKMuHDyDMVsxtVsJHIEVY',
					canvasTwoId: 'nHLyuIhBZnCVKMuHDyZMVsxtVsJHIEVY',
				},

				title: '标题',
				pickerShow: true, //年份选择弹出
				columns: [
					['2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031',
					'2032', '2033', '2034', '2035', '2036', '2037', '2038', '2039', '2040']
				],

				selectYear: '', //选择的年份

				showSheet: false,
				selectDayIndex: new Date().getDate() - 1,
				selectMonthIndex: 0,
				show: false,

				//是否显示曲线图
				isShowChars: false,

				//选择日期类型
				dateType: 'day',

				//日期选择下标
				dateSelectIndex: 0,
				cWidth: 750,
				cHeight: 400,

				//当月最后一天
				lastDayMonth: 31,

				//记录当月一号是星期几
				dayWeek: 0,


				//拿到当前的时期
				nowDate: '',
				//查询图表数据的日期单位
				dateUnit: {
					day: "day",
					month: "month",
					year: "year"
				},


				//日期分组
				dataDateGrouping: new Map(),

				backgroundColor: ['normal', 'warn', 'wechat'],

				//uchars 需要的图表数据
				categories: [],
				dataOne: [],
				dataTwo: [],
				//甲醛和TVOC的平均值
				avg: [],
				//气体id
				gasId: [],

				showDatePicker: true,
				//查询时间相关
				selectYearIndex: 11,
				beforeTwentyYear: new Date().getFullYear() - 12,
				year: new Date().getFullYear(),
				month: new Date().getMonth() + 1,
				customDate: '',
				dateUnitD: ''

			}
		},

		onReady() {
			//这里的 750 对应 css .charts 的 width
			this.cWidth = uni.upx2px(750);
			//这里的 500 对应 css .charts 的 height
			this.cHeight = uni.upx2px(400);
		},

		onLoad() {
			//获取到当月最后一天
			this.getMonthLastDay();
			this.nowDate = this.formatDateTime(new Date(), "MM月dd日");

			//初始化图表数据
			this.getSameDay(new Date(), this.dateUnit.day);

			//初始化查询
			let mac = this.vuex_select_equipment.mac
			let date = this.formatDateTime(new Date(), "yyyy-MM-dd")
			this.searchDayAvg(date, this.dateUnit.day, mac);
		},

		methods: {

			//查询一段时间内总数据的平均值
			async searchDayAvg(date, timeUnit, equipmentMac) {
				let queryParam = {
					date,
					timeUnit,
					equipmentMac
				};
				const resp = await searchDayAvgData(queryParam);
				//对查询出的数据进行处理
				this.dataProcessing(resp.data.items);
			},


			//数据处理
			dataProcessing(items) {
				this.dataDateGrouping = new Map();
				//传感器日 月 年平均值
				let dataOne = items[0];
				//警告值1
				let warningValueOne = dataOne.alarm_rang.split(':');
				let dataTwo = items[1];
				//警告值2
				let warningValueTwo = dataTwo.alarm_rang.split(':');
				//循环处理数据
				for (var i = 0; i < dataOne.data.length; i++) {
					if (dataOne.data[i] != null) {
						let leveOne = this.getDangerGrade(dataOne.data[i], warningValueOne);
						let leveTwo = this.getDangerGrade(dataOne.data[i], warningValueTwo);
						if (leveOne > leveTwo) {
							this.dataDateGrouping.set(i, this.backgroundColor[leveOne]);
						} else {
							this.dataDateGrouping.set(i, this.backgroundColor[leveTwo]);
						}
					} else {
						this.dataDateGrouping.set(i, "");
					}

				}
			},

			//判断数值的危险等级
			getDangerGrade(currentValue, dangerNumbers) {
				for (var i = 0; i < dangerNumbers.length; i++) {
					if (parseFloat(currentValue) < parseInt(dangerNumbers[i])) {
						return i; //危险等级 0 良好 1  警告 2 超标
					}
				}
				//如果全部都是大于就是最危险的等级
				return 2;

			},

			//是否禁用某个日期的选择 日和月
			isForbiddenDay(index) {
				//index > new Date().getDate() -1 || year > new Date().getFullYear()
				var date = new Date();
				if (this.month > date.getMonth() + 1) {
					return true;
				}

				if (this.month == date.getMonth() + 1) {
					//判断天是否大于
					if (index > date.getDate() - 1) {
						return true;
					}
				}
				return false;
			},
			//是否禁用某个日期的选择年
			isForbiddenYear(index) {
				var date = new Date();
				if (this.year > date.getFullYear()) {
					return true;
				}

				if (this.year == date.getFullYear()) {
					//判断天是否大于
					if (index > date.getMonth()) {
						return true;
					}
				}
				return false;
			},
			//子组件日期切换调用的方式
			switchingTime(data) {
				this.selectDayIndex = 0;
				this.selectMonthIndex = 0;
				//获取当前日期
				var date = new Date();
				let queryDate;
				this.getMonthLastDay(data - 1);
				if (this.dateType == 'day') {
					this.month = data;
					//查询平均值数据  
					queryDate = this.formatDateTime(new Date(date.getFullYear(), this.month - 1, 1), "yyyy-MM-dd");
				} else {
					this.year = data;
					queryDate = this.formatDateTime(new Date(this.year, 1, 1), "yyyy-MM-dd");
				}
				this.searchDayAvg(queryDate, this.dateType, this.vuex_select_equipment.mac);
			},

			//查询当前设备 当天的数据
			async getSameDay(date, dateUnit) {
				//请求参数
				let param = {
					date: this.formatDateTime(date, "yyyy-MM-dd"),
					timeUnit: dateUnit,
					eqId: this.vuex_select_equipment.id,
					equipmentMac: this.vuex_select_equipment.mac,
				};
				const resp = await searchData(param);
				let respData = resp.data;

				//图表上显示的时间
				let dataTime = [];

				//曲线数据第一个图表
				let dataNumberOne = [];
				//曲线数据第二个图表
				let dataNumberTwo = [];

				//如果dates 是空不进行处理
				if (respData) {
					//获取到时间数据
					for (let item of respData.dates) {
						dataTime.push(item);
					}

					//获取到检测数据1
					for (let item of respData.items[0].data) {
						dataNumberOne.push(item ? item : 0);
					}

					//获取到检测数据2
					for (let item of respData.items[1].data) {
						dataNumberTwo.push(item ? item : 0);
					}


					this.gasId[0] = respData.items[0].gasId;
					this.gasId[1] = respData.items[1].gasId;

					//获取 甲醛和tvoc 平均值
					this.avg[0] = respData.items[0].avgValue;
					this.avg[1] = respData.items[1].avgValue;
				}



				//组件赋值
				this.categories = dataTime;
				this.dataOne = dataNumberOne;
				this.dataTwo = dataNumberTwo;

				//解除loader 状态
				uni.hideLoading();
				//显示图表数据
				this.isShowChars = true;
				this.close();

			},

			//获取到当月最后一天
			getMonthLastDay(monthParan) {
				var monthNew = monthParan ? monthParan : new Date().getMonth();
				let year = this.formatDateTime(new Date(), "yyyy");
				let month = this.formatDateTime(new Date(year, monthNew, 1), "MM");
				this.lastDayMonth = this.getLastDayOfMonth(year, month);
				var firstDayOfWeek = this.getFirstDayOfWeek(year, month);
				this.dayWeek = firstDayOfWeek === 0 ? 7 : firstDayOfWeek;
			},


			//选择年份回调
			change(e) {
				this.selectYear = e;
			},

			//自定义格式化
			formatDateTime(date, format) {
				const o = {
					'M+': date.getMonth() + 1, // 月份
					'd+': date.getDate(), // 日
					'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
					'H+': date.getHours(), // 小时
					'm+': date.getMinutes(), // 分
					's+': date.getSeconds(), // 秒
					'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
					S: date.getMilliseconds(), // 毫秒
					a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
					A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
				};
				if (/(y+)/.test(format)) {
					format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				for (let k in o) {
					if (new RegExp('(' + k + ')').test(format)) {
						format = format.replace(
							RegExp.$1,
							RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
						);
					}
				}
				return format;
			},


			//获取每个月的1号是 星期几?
			getFirstDayOfWeek(year, month) {
				// 创建一个日期对象，参数为指定的年份和月份（月份从0开始，所以需要减去1）
				var date = new Date(year, month - 1, 1);

				// 获取星期几，返回值为0-6，其中0表示星期日，1表示星期一，以此类推
				var dayOfWeek = date.getDay();

				return dayOfWeek;
			},

			//获取到每个月的最后一天
			getLastDayOfMonth(year, month) {
				// 创建下个月的第一天
				var nextMonth = new Date(year, month, 1);
				// 将下个月的第一天往前推一天，即为当前月的最后一天
				var lastDay = new Date(nextMonth.getTime() - 86400000).getDate();

				return lastDay;
			},


			selectClick(index) {
			},

			//确认选择日期
			verifyDay() {
				//隐藏掉chars 图表
				this.isShowChars = false;

				//设置请求信息
				uni.showLoading({
					title: '查询中...',
					mask: true
				})

				//判断用户选择查询的是日还是月
				if (this.dateType == 'day') {
					this.customDate = new Date(this.year, this.month - 1, this.selectDayIndex + 1);
					this.dateUnitD = this.dateUnit.day;
					//获取到选择的时间
					this.nowDate = this.formatDateTime(this.customDate, "MM月dd日");

				} else if (this.dateType == 'month') {
					this.customDate = new Date(this.year, this.selectMonthIndex, 1);
					this.dateUnitD = this.dateUnit.month;
					//获取到选择的时间
					this.nowDate = this.formatDateTime(this.customDate, "yyyy年MM月");
				} else {
					this.customDate = new Date(this.beforeTwentyYear + this.selectYearIndex + 1, 1, 1);
					this.dateUnitD = this.dateUnit.year;
					//获取到选择的时间
					this.nowDate = this.formatDateTime(this.customDate, "yyyy年");
				}

				//重新查询图表数据
				this.getSameDay(this.customDate, this.dateUnitD);


			},
			
			pickerCancel(){
				this.pickerShow = false;
			},
			
			confirmPicker(e){
				this.pickerShow = false;
			},
			

			close() {
				this.show = false;
			},

			open() {
				this.show = true;
			},

			dateSelectIndexMethod(index, type) {
				this.dateSelectIndex = index;
				this.dateType = type;

				//收集日期
				let queryDate;

				//index 进行年月日区分 0 日 1 月 2 年
				var date = new Date();
				if (index == 0) {
					this.selectDayIndex = date.getDate() - 1;
				} else if (index == 1) {
					//再重新赋值
					this.selectMonthIndex = date.getMonth();
				} else {
					this.selectYear = date.getFullYear();
				}

				//调用查询平均值数据
				let newDate = this.formatDateTime(date, "yyyy-MM-dd");
				this.searchDayAvg(newDate, type, this.vuex_select_equipment.mac);

				//确认查询数据
				this.verifyDay();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.data-picker {
		font-size: 28rpx;
		font-weight: 700;
		justify-content: flex-end;
		padding: 40rpx 32rpx 0;
		color: #6477F4;
	}

	.charts {
		width: 750rpx;
		height: 500rpx;
	}

	.navigation {
		position: relative;
		width: 90%;
		height: 180rpx;
		margin: 0 auto;

		.select_date {
			top: 40rpx;
			left: 0;
			display: flex;
			justify-content: space-evenly;
			width: 100%;

			.stats {
				background: #353535;
				color: white;
			}

			//左边倒角
			.border_left {
				border-top-left-radius: 30rpx;
				border-bottom-left-radius: 30rpx;
			}

			//右边倒角
			.border_right {
				border-top-right-radius: 30rpx;
				border-bottom-right-radius: 30rpx;
			}


			.active {
				background: rgb(24, 24, 24);
				color: black;
				width: 150rpx;
				height: 80rpx;
				background: #BC9C5E;
			}

			.item {
				width: 180px;
				height: 50px;
				text-align: center;
				line-height: 50px;
			}
		}
	}

	.sensor {
		display: flex;
		justify-content: space-between;
		width: 100%;
		height: 340rpx;
		position: relative;

		.content {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: absolute;
			top: 80rpx;
			left: 60rpx;
		}

		.content_two {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: absolute;
			top: 80rpx;
			right: 40rpx;
		}
	}


	.date_table {
		display: flex;
		justify-content: center;
		width: 100%;
		margin-right: 30rpx;
		font-size: 42rpx;
		align-items: center;
		justify-content: flex-end;
	}

	.table_unit {
		display: flex;
		justify-content: center;
		align-items: flex-end;
	}

	.history {
		width: 100%;
		text-align: center;
		position: relative;

		.history_text {
			position: absolute;
			left: 33%;
			top: 60rpx;
		}
	}

	.forbidden {
		color: #727272 !important;
	}


	//日期选择 根据数值 来渲染出当天的颜色

	//数值正常显示
	.normal {
		background: rgba(103, 213, 191, 0.2);
	}

	//警告显示	
	.warn {
		background: rgba(250, 203, 35, 0.2);
	}

	//危险显示
	.wechat {
		background: rgba(246, 105, 3, 0.5);
	}

	/**日*/
	.popup_day {
		height: 900rpx;
		background: rgb(53, 53, 53);
		border-top-left-radius: 50rpx;
		border-top-right-radius: 50rpx;


		.week {
			display: flex;
			justify-content: space-evenly;
		}

		.day {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			padding: 1rem;
			height: 500rpx;



			.item_no {
				width: 90rpx;
				height: 60rpx;
				margin-left: 9rpx;
			}

			.active {
				border: 1px solid #BD9D5F;
			}



			.item {
				width: 88rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				margin-left: 9rpx;
				border-radius: 2px;
			}
		}

		.btn {
			width: 500rpx;
			height: 100rpx;
			background: #BD9D5F;
			border-radius: 50rpx;
			text-align: center;
			line-height: 100rpx;
			margin: 0 auto;
		}
	}

	/**月**/
	.popup_month {
		height: 900rpx;
		background: rgb(53, 53, 53);
		border-top-left-radius: 50rpx;
		border-top-right-radius: 50rpx;

		.week {
			display: flex;
			justify-content: space-evenly;
		}

		.month {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			padding: 1rem;
			height: 500rpx;

			.item_no {
				width: 90rpx;
				height: 60rpx;
				margin-left: 9rpx;
			}

			.active {
				border: 1px solid #BD9D5F;
			}

			.item {
				width: 120rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				margin-left: 16rpx;
				border-radius: 2px;
			}
		}

		.btn {
			width: 500rpx;
			height: 100rpx;
			background: #BD9D5F;
			border-radius: 50rpx;
			text-align: center;
			line-height: 100rpx;
			margin: 0 auto;
		}
	}


	/**年**/
	.popup_years {
		height: 900rpx;
		background: rgb(53, 53, 53);
		border-top-left-radius: 50rpx;
		border-top-right-radius: 50rpx;

		.week {
			display: flex;
			justify-content: space-evenly;
		}

		.years {
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			align-items: center;
			padding: 0.5rem;

			.year_item {
				width: 180rpx;
				height: 80rpx;
				text-align: center;
				line-height: 80rpx;
				margin-top: 20rpx;
				padding-left: 20rpx;
				padding-right: 20rpx;
				border-radius: 30rpx;
			}

			.select_year {
				font-size: 20rpx;
				padding: 30rpx;
				width: 95%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;
				background: #181818;
				border-radius: 60rpx;
			}

			.item_no {
				width: 90rpx;
				height: 60rpx;
				margin-left: 9rpx;
			}

			.active {
				border: 1px solid #BD9D5F;
			}

			.item {
				width: 120rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				border-radius: 20rpx;
				margin-left: 16rpx;
				border-radius: 2px;
			}
		}

		.btn {
			width: 500rpx;
			height: 100rpx;
			background: #BD9D5F;
			border-radius: 50rpx;
			text-align: center;
			line-height: 100rpx;
			margin: 0 auto;
		}
	}
</style>